package com.taotao.springboot2.common.mybatis.plus.update.fill;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 创建人更新人处理
 */
@Component
@Slf4j
@Primary
public class MybatisPlusUpdateHandler implements MetaObjectHandler {


    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime updateTime1 = DaoContext.getUpdateTime();
        if (null == updateTime1) {
            updateTime1 = LocalDateTime.now();
        }

        if (Objects.isNull(this.getFieldValByName(DaoContext.CREATE_TIME, metaObject))) {
            this.setFieldValByName(DaoContext.CREATE_TIME, updateTime1, metaObject);
        }

        if (Objects.isNull(this.getFieldValByName(DaoContext.UPDATE_TIME, metaObject))) {
            this.setFieldValByName(DaoContext.UPDATE_TIME, updateTime1, metaObject);
        }


        Long updateId1 = DaoContext.getUpdateId();
        if (null == updateId1) {
            return;
        }
        if (Objects.isNull(this.getFieldValByName(DaoContext.CREATE_ID, metaObject))) {
            this.setFieldValByName(DaoContext.CREATE_ID, updateId1, metaObject);
        }

        if (Objects.isNull(this.getFieldValByName(DaoContext.UPDATE_ID, metaObject))) {
            this.setFieldValByName(DaoContext.UPDATE_ID, updateId1, metaObject);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LocalDateTime updateTime1 = DaoContext.getUpdateTime();
        if (null == updateTime1) {
            updateTime1 = LocalDateTime.now();
        }


        if (Objects.isNull(this.getFieldValByName(DaoContext.UPDATE_TIME, metaObject))) {
            this.setFieldValByName(DaoContext.UPDATE_TIME, updateTime1, metaObject);
        }


        Long updateId1 = DaoContext.getUpdateId();
        if (null == updateId1) {
            return;
        }

        if (Objects.isNull(this.getFieldValByName(DaoContext.UPDATE_ID, metaObject))) {
            this.setFieldValByName(DaoContext.UPDATE_ID, updateId1, metaObject);
        }
    }


}
